package src.dp.stock;

public class no188 {//股票4，最多可买卖 k 次

    public int maxProfit(int k, int[] prices) {
        int len = prices.length;
        int[][] dp = new int[len][2 * k + 1];


        dp[0][0] = 0;//不操作
        for (int i = 1; i < 2 * k; i = i + 2) {
            dp[0][i] = -prices[0];  //奇数为第k次持有
        }
        for (int i = 2; i < 2 * k; i += 2) {
            dp[0][i] = 0;  //偶数为第k次不持有
        }

        for (int i = 1; i < len; i++) {
            //dp[i][0] = dp[i - 1][0];
            for (int j = 1; j <= 2 * k; j++) {
                //持有时 -prices[i]
                if (j % 2 == 1) dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - 1] - prices[i]);
                //不持有时 +prices[i]
                else dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - 1] + prices[i]);
            }
        }
        return dp[len - 1][2 * k];
    }
}
